import roundNumber from './roundNumber'
/**
 * 将十六进制颜色转换为RGBA格式
 * @param {string} hex 十六进制颜色字符串，例如"#RRGGBB"或"#RRGGBBff"或"#RGB"(ps:#RGB=#RGBRGB)
 * @param {number} opacity 透明度，取值范围为0到1之间的数字
 * @returns {string | null} 返回RGBA格式的颜色字符串，例如"rgba(255, 0, 0, 0.2)"
 */
function colorHexToRgba(hex: string, opacity: number): string | null {
  let rgba = null
  let typeOfHex: null | number = null
  if (hex.includes('rgb')) {
    rgba = hex
    return rgba
  }
  hex = hex.trim()
  if (typeof opacity != 'number' || !(opacity >= 0 && opacity <= 1)) {
    console.warn(`The opacity Range number is 0 to 1 ,otherwise will be 1`)
    opacity = 1
  }
  const hexAllRegMap: { [index: number]: RegExp } = {
    0: new RegExp(/^#([0-9a-fA-F]){3}$/),
    1: new RegExp(/^#([0-9a-fA-F]){6}$/),
    2: new RegExp(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})$/)
  }

  for (const i of Object.keys(hexAllRegMap)) {
    if (hexAllRegMap[+i].test(hex)) {
      typeOfHex = +i
      break
    }
  }
  if (typeOfHex == null) return rgba
  if (typeOfHex === 0) hex = '#' + hex.slice(1) + hex.slice(1)
  const r = parseInt('0x' + hex.slice(1, 3))
  const g = parseInt('0x' + hex.slice(3, 5))
  const b = parseInt('0x' + hex.slice(5, 7))
  if (typeOfHex === 2) {
    opacity = parseInt('0x' + hex.slice(7, 9)) / 255 // 除以 255就得到小数的透明度
  }
  rgba =
    'rgba(' + r + ',' + g + ',' + b + ',' + roundNumber(opacity, 2, 10) + ')'
  return rgba
}

export default colorHexToRgba
